package com.qqt.csr.im.service.sensitiveword;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.houbb.sensitive.word.api.IWordContext;
import com.github.houbb.sensitive.word.api.IWordResult;
import com.github.houbb.sensitive.word.api.IWordResultHandler;
import com.github.houbb.sensitive.word.utils.InnerWordCharUtils;
import com.github.houbb.sensitive.word.utils.InnerWordTagUtils;
import com.google.common.collect.Lists;
import com.qqt.csr.common.utils.JsonUtil;
import com.qqt.csr.im.dto.SensitiveWordResultDTO;
import com.qqt.csr.im.dto.SensitiveWordTagDTO;
import com.qqt.csr.im.entity.Account;
import com.qqt.csr.im.enums.SensitiveWordRepoType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class SensitiveWordFilterResultHandler implements IWordResultHandler<SensitiveWordResultDTO.Word> {

    @Override
    public SensitiveWordResultDTO.Word handle(IWordResult wordResult, IWordContext wordContext, String originalText) {
        if (wordResult == null) {
            return null;
        }

        // 通过坐标截取出命中的敏感词
        String word = InnerWordCharUtils.getString(originalText.toCharArray(), wordResult);
        // 获取 tags
        Set<String> wordTags = InnerWordTagUtils.tags(word, wordContext);
        if(CollectionUtils.isEmpty(wordTags)){
            return null;
        }

        List<SensitiveWordTagDTO> tagDTOList = new ArrayList<>();
        for (String wordTag : wordTags) {
            if (StringUtils.isBlank(wordTag)) {
                continue;
            }

            // 标签格式:租户id|词库id
            String[] data = StringUtils.split(wordTag, StringPool.PIPE);
            if (data.length < 2) {
                continue;
            }
            SensitiveWordTagDTO tagDTO = new SensitiveWordTagDTO()
                    .setTenantId(data[0])
                    .setRepId(Long.parseLong(data[1]));
            tagDTOList.add(tagDTO);
        }

        if(CollectionUtils.isEmpty(tagDTOList)){
            return null;
        }

        SensitiveWordResultDTO.Word wordInfo = new SensitiveWordResultDTO.Word();
        wordInfo.setStartIndex(wordResult.startIndex());
        wordInfo.setEndIndex(wordResult.endIndex());
        wordInfo.setWord(word);
        wordInfo.setTagDTOList(tagDTOList);
        return wordInfo;
    }
}
